/**
 * 批次数据处理工具函数
 */

/**
 * 修复批次数据状态不一致的问题
 * @param {Object} batch - 批次数据
 * @returns {Object} 修复后的批次数据
 */
export const fixBatchStatusInconsistency = batch => {
  if (!batch) return batch

  const fixedBatch = { ...batch }

  // 修复导入完成但importStatus不是completed的情况
  if (batch.status === 'import_completed' && batch.importStatus !== 'completed') {
    fixedBatch.importStatus = 'completed'
    fixedBatch.importProgress = 100
    console.warn(
      `修复批次 ${batch.id} 状态不一致: status=import_completed 但 importStatus=${batch.importStatus}`
    )
  }

  // 修复导入中但status不是importing的情况
  if (batch.importStatus === 'importing' && batch.status !== 'importing') {
    fixedBatch.status = 'importing'
    console.warn(
      `修复批次 ${batch.id} 状态不一致: importStatus=importing 但 status=${batch.status}`
    )
  }

  // 修复导入停止但status不是import_stopped的情况
  if (batch.importStatus === 'stopped' && batch.status !== 'import_stopped') {
    fixedBatch.status = 'import_stopped'
    console.warn(`修复批次 ${batch.id} 状态不一致: importStatus=stopped 但 status=${batch.status}`)
  }

  return fixedBatch
}

/**
 * 为批次数据添加默认值
 * @param {Object} batch - 批次数据
 * @returns {Object} 处理后的批次数据
 */
export const addBatchDefaults = batch => {
  if (!batch) {
    return {
      matchingProgress: 0,
      vectorProgress: 0,
      totalInfo: 0,
      totalImages: 0,
      identifiedStyles: 0,
      identifiedColors: 0,
      anomalies: {
        naming: 0,
        emptyImage: 0,
        emptyInfo: 0,
        imageOnly: 0,
      },
    }
  }

  // 先修复状态不一致问题
  const fixedBatch = fixBatchStatusInconsistency(batch)

  return {
    ...fixedBatch,
    matchingProgress: fixedBatch.matchingProgress ?? 0,
    vectorProgress: fixedBatch.vectorProgress ?? 0,
    totalInfo: fixedBatch.totalInfo ?? 0,
    totalImages: fixedBatch.totalImages ?? 0,
    identifiedStyles: fixedBatch.identifiedStyles ?? 0,
    identifiedColors: fixedBatch.identifiedColors ?? 0,
    anomalies: {
      naming: fixedBatch.anomalies?.naming ?? 0,
      emptyImage: fixedBatch.anomalies?.emptyImage ?? 0,
      emptyInfo: fixedBatch.anomalies?.emptyInfo ?? 0,
      imageOnly: fixedBatch.anomalies?.imageOnly ?? 0,
      ...fixedBatch.anomalies,
    },
  }
}

/**
 * 处理批次列表响应数据
 * @param {Object} response - API响应数据（已经是 response.data）
 * @returns {Object} 处理后的数据，确保包含 list 属性
 */
export const processBatchesResponse = response => {
  // 确保 response 存在
  if (!response) {
    return { list: [] }
  }

  // 如果 response 有 list 属性
  if (response.list && Array.isArray(response.list)) {
    return {
      ...response,
      list: response.list.map(addBatchDefaults),
    }
  }

  // 如果 response 本身是数组
  if (Array.isArray(response)) {
    return {
      list: response.map(addBatchDefaults),
    }
  }

  // 如果 response 是对象但没有 list 属性，尝试其他可能的属性名
  if (typeof response === 'object' && response !== null) {
    // 检查是否有其他可能的数组属性
    const possibleArrayProps = ['data', 'items', 'results', 'batches']
    for (const prop of possibleArrayProps) {
      if (response[prop] && Array.isArray(response[prop])) {
        return {
          ...response,
          list: response[prop].map(addBatchDefaults),
        }
      }
    }
  }

  // 默认返回空列表
  return { list: [] }
}

/**
 * 测试状态修复逻辑
 * 仅在开发环境下运行
 */
export const testStatusFix = () => {
  if (process.env.NODE_ENV !== 'development') return

  console.log('🧪 测试批次状态修复逻辑...')

  // 测试用例1: 导入完成但importStatus不是completed
  const testCase1 = {
    id: '6',
    name: 'BrandA-2025SS',
    brand: 'BrandA',
    season: '2025SS',
    status: 'import_completed',
    importTime: '2025-08-10 14:22',
    importProgress: 100,
    importStatus: 'importing',
    matchingProgress: 0,
    vectorProgress: 0,
    totalInfo: 156,
    totalImages: 142,
    identifiedStyles: 23,
    identifiedColors: 89,
    anomalies: {
      naming: 12,
      emptyImage: 6,
      emptyInfo: 3,
      imageOnly: 8,
    },
  }

  const fixed1 = fixBatchStatusInconsistency(testCase1)
  console.log('测试用例1 - 修复前:', testCase1.status, testCase1.importStatus)
  console.log('测试用例1 - 修复后:', fixed1.status, fixed1.importStatus)
  console.log(
    '✅ 测试用例1 通过:',
    fixed1.status === 'import_completed' && fixed1.importStatus === 'completed'
  )

  // 测试用例2: 导入中但status不是importing
  const testCase2 = {
    id: '7',
    name: 'BrandB-2025FW',
    brand: 'BrandB',
    season: '2025FW',
    status: 'new',
    importTime: null,
    importProgress: 45,
    importStatus: 'importing',
    matchingProgress: 0,
    vectorProgress: 0,
    totalInfo: 0,
    totalImages: 0,
    identifiedStyles: 0,
    identifiedColors: 0,
    anomalies: {
      naming: 0,
      emptyImage: 0,
      emptyInfo: 0,
      imageOnly: 0,
    },
  }

  const fixed2 = fixBatchStatusInconsistency(testCase2)
  console.log('测试用例2 - 修复前:', testCase2.status, testCase2.importStatus)
  console.log('测试用例2 - 修复后:', fixed2.status, fixed2.importStatus)
  console.log(
    '✅ 测试用例2 通过:',
    fixed2.status === 'importing' && fixed2.importStatus === 'importing'
  )

  // 测试用例3: 导入停止但status不是import_stopped
  const testCase3 = {
    id: '8',
    name: 'BrandC-2025SS',
    brand: 'BrandC',
    season: '2025SS',
    status: 'new',
    importTime: null,
    importProgress: 30,
    importStatus: 'stopped',
    matchingProgress: 0,
    vectorProgress: 0,
    totalInfo: 0,
    totalImages: 0,
    identifiedStyles: 0,
    identifiedColors: 0,
    anomalies: {
      naming: 0,
      emptyImage: 0,
      emptyInfo: 0,
      imageOnly: 0,
    },
  }

  const fixed3 = fixBatchStatusInconsistency(testCase3)
  console.log('测试用例3 - 修复前:', testCase3.status, testCase3.importStatus)
  console.log('测试用例3 - 修复后:', fixed3.status, fixed3.importStatus)
  console.log(
    '✅ 测试用例3 通过:',
    fixed3.status === 'import_stopped' && fixed3.importStatus === 'stopped'
  )

  console.log('🎉 所有测试用例完成!')
}
